<template>
	<div class="search-content drag">
		<!-- 搜索框 -->
		<div class="search-input no-drag">
			<div class="wrap">
				<el-icon>
					<Search color="#b1b1b1" size="30" />
				</el-icon>
				<input type="text" id="search-input" v-model="keyword" @click="handleSearchInput" />
				<el-icon v-if="props.showClose" class="close-icon" @click="handleClose">
					<Close color="#b1b1b1" size="20" style="cursor: pointer" />
				</el-icon>
			</div>
			<slot></slot>
		</div>
	</div>
</template>
<script setup lang="ts">
import { reqSearch } from '@/api/contact'
import { KeywordResult } from '@/api/contact/type'

const props = defineProps(['showClose'])

const emits = defineEmits(['update:showClose', 'getDataList'])

// 搜索关键字
let keyword = ref<string>('')
let timer: any = null
// 搜索框回调
const handleSearchInput = () => {
	emits('update:showClose', true)
}

// 关闭图标回调
const handleClose = () => {
	emits('update:showClose', false)
	keyword.value = ''
}

// 输入框搜索关键字
watch(keyword, () => {
	if (timer) {
		clearTimeout(timer)
	}
	timer = setTimeout(() => {
		handleSearchResutl()
	}, 1000)
})

const handleSearchResutl = async () => {
	if (!keyword.value) return emits('getDataList', { friendList: [], groupList: [] })
	// 搜索相关人或者群聊
	let res: KeywordResult = await reqSearch(keyword.value)
	if (res.code === 200) {
		emits('getDataList', res.data)
	}
}
</script>

<style scoped lang="scss">
.search-content {
	width: 100%;
	height: 50px;
	display: flex;
	justify-content: center;
	align-items: center;

	.search-input {
		width: 200px;
		height: 30px;
		display: flex;
		align-items: center;

		.wrap {
			flex: 1;
			height: 100%;
			border-radius: 20px;
			box-sizing: border-box;
			padding: 0 15px 0 15px;
			display: flex;
			align-items: center;
			background-color: var(--search-input-bg-color);
			position: relative;

			input {
				width: 100px;
				height: 20px;
				margin-left: 5px;
				border: none;
				background-color: var(--search-input-bg-color);
				font-size: 13px;
			}

			.close-icon {
				position: absolute;
				top: 50%;
				transform: translateY(-50%);
				right: 5px;
			}
		}
	}
}
</style>
